package com.chujian.framework.ws.support.srv;


import cn.hutool.http.HttpUtil;
import com.chujian.framework.ws.WsConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 握手认证拦截器
 */
@Slf4j
public abstract class AbstractHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

        // 请求参数解析
        Map<String, String> paramMap = HttpUtil.decodeParamMap(request.getURI().getQuery(), StandardCharsets.UTF_8);
        String id = paramMap.get(WsConst.SESSION_CLI_ID);
        String key = paramMap.get(WsConst.SESSION_CLI_KEY);
        String token = paramMap.get(WsConst.SESSION_CLI_TOKEN);

        if (!checkAuthInfo(id, key, token)) {
            log.error("非法客户端连接，id={}, key={}, token={}", id, key, token);
            return false;
        }

        attributes.put(WsConst.SESSION_CLI_ID, id);
        attributes.put(WsConst.SESSION_CLI_KEY, key);
        attributes.put(WsConst.SESSION_CLI_TOKEN, token);

        // 放行
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }

    protected abstract boolean checkAuthInfo(String cliId, String cliKey, String cliToken);


}
